// 导入模块
import Request from 'luch-request'
import { useUserStore } from '@/stores/user.js'
// 实例化网络请求
const http = new Request({
	// 接口基地址
	baseURL: 'https://consult-api.itheima.net/',
	custom: {
		loading: true,
	},
})

// 请求拦截器
http.interceptors.request.use(
	function (config) {
		const userStore = useUserStore()
		const defaltHeader = {}
		if (userStore.token && !whiteList.includes(config.url)) {
			defaltHeader.Authorization = 'Bearer ' + userStore.token
		}
		if (config.custom.loading) {
			// 显示加载状态提示
			uni.showLoading({ title: '正在加载...', mask: true })
		}
		// 定义头信息，并保证接口调用传递的头信息
		// 能够覆盖在拦截器定义的头信息
		config.header = {
			...defaltHeader,
			...config.header,
		}

		return config
	},
	function (error) {
		return Promise.reject(error)
	}
)

// 响应拦截器
http.interceptors.response.use(
	function ({ statusCode, data, config }) {
		// 解构出响应主体
		uni.hideLoading()
		return data
	},
	function (error) {
		uni.hideLoading()
		if (error.statusCode == 401) reLogin()
		return Promise.reject(error)
	}
)
const whiteList = ['/code', '/login', 'login/password']
// tabBar页面路径
const tabBarList = [
	'pages/index/index',
	'pages/wiki/index',
	'pages/notify/index',
	'pages/my/index',
]
const reLogin = () => {
	const pageStack = getCurrentPages()
	const currentPage = pageStack[pageStack.length - 1]
	const redirectURL = currentPage.$page.fullPath
	const openType = tabBarList.includes(currentPage.route)
		? 'switchTab'
		: 'redirectTo'
	const userStore = useUserStore()
	userStore.openType = openType
	userStore.redirectUrl = redirectURL
	uni.redirectTo({
		url: '/pages/login/login',
	})
}

// 导出配置好的模网络模块
export { http }
